using System;
using UnityEngine;
using UnityEngine.UI;

namespace JH
{
    /// <summary>
    /// 当Toggle设置为false时，同时关闭Toggle的图片显示
    /// </summary>
    [ExecuteAlways]
    public class ActiveInactiveOnToggleSwitch : BaseToggleCustomEvent
    {
        /// <summary>
        ///  默认状态
        /// </summary>
        [SerializeField, Header("默认状态")] private Graphic background;

        /// <summary>
        ///  选中状态
        /// </summary>
        [SerializeField, Header("选中状态")] private Graphic checkmark;

        protected override void OnValidate()
        {
            base.OnValidate();
            background = toggle.targetGraphic.gameObject.GetComponent<Graphic>();
            checkmark = toggle.graphic.gameObject.GetComponent<Graphic>();
        }

        private void Awake()
        {
            //运行时把背景和选中状态的图片实例化出来一份新的，原来的不要了
            if (!Application.isPlaying) return;
            var oldBackground = background;
            var oldCheck = checkmark;
            background = Instantiate(background, transform);
            checkmark = Instantiate(checkmark, transform);
            Destroy(oldBackground);
            Destroy(oldCheck);
        }

        protected override void OnToggleOn()
        {
            base.OnToggleOn();
            ActiveInactivePart(true);
        }

        protected override void OnToggleOff()
        {
            base.OnToggleOff();
            ActiveInactivePart(false);
        }

        /// <summary>
        ///  toggle为true时，激活选中状态，关闭默认状态
        ///  toggle为false时，激活默认状态，关闭选中状态
        /// </summary>
        private void ActiveInactivePart(bool arg0)
        {
            background.gameObject.SetActive(!arg0);
            checkmark.gameObject.SetActive(arg0);
        }
    }
}